package com.yhy.admin.service.mng;

import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.yhy.admin.dao.MenuMngDao;
import com.yhy.admin.dto.MenuDTO;
import com.yhy.admin.service.MenuLanService;
import com.yhy.admin.service.MenuService;
import com.yhy.admin.vo.MenuBuildVo;
import com.yhy.admin.vo.MenuLanVO;
import com.yhy.admin.vo.MenuMetaVo;
import com.yhy.admin.vo.mng.MenuMngVO;
import com.yhy.admin.vo.MenuVO;
import com.yhy.common.constants.BusMenuType;
import com.yhy.common.constants.BusModuleType;
import com.yhy.common.constants.BusPrivCode;
import com.yhy.common.constants.OperateType;
import com.yhy.common.dto.BaseEntity;
import com.yhy.common.exception.BusinessException;
import com.yhy.common.service.BaseMngService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/*
 *
 *  * *
 *  *  * <br>
 *  *  * <b>功能：</b><br>
 *  *  * <b>作者：</b>yanghuiyaun<br>
 *  *  * <b>日期：</b> 19-11-13 下午4:25 <br>
 *  *  * <b>版权所有：<b>版权所有(C) 2019<br>
 *  *
 *
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MenuMngService extends BaseMngService<MenuDTO, MenuMngVO> {

    @Autowired
    private MenuMngDao menuMngDao;

    @Autowired
    private MenuService menuService;
    @Autowired
    private MenuLanService menuLanService;

    @Override
    protected MenuMngDao getBaseMngDao() {
        return menuMngDao;
    }

    @Override
    public String getBusModule() {
        return BusModuleType.MD_MENU_MNG.getVal();
    }

    @Override
    public MenuService getBaseMainService() {
        return menuService;
    }

    @Override
    protected void processOfToAdd(MenuDTO baseDTO) {
        super.processOfToAdd(baseDTO);
        MenuMngVO mngVO = baseDTO.getBusMainData();
        mngVO.setEnableFlag("Y");
        mngVO.setMenuType(BusMenuType.MENU_INNER.getVal());
        mngVO.setIsAdmin("0");
        mngVO.setIsVisable("0");
        mngVO.setIsWorkflow("0");
        mngVO.setSort(99);
    }

    @Override
    protected void beforeSaveOfProcess(MenuDTO baseDTO) {
        super.beforeSaveOfProcess(baseDTO);
        MenuMngVO mngVO = baseDTO.getBusMainData();
        //权限按钮标识
        if(BusMenuType.MENU_PRIV.getVal().equals(mngVO.getMenuType())) {
            //设置为不可见
            mngVO.setIsVisable("0");
        }
    }

    @Override
    protected void afterProcessCustomDataOfSave(MenuDTO baseDTO) {
        super.afterProcessCustomDataOfSave(baseDTO);
        String mainId = baseDTO.getBusMainData().getId();
        Map<String,String> existsSets = Maps.newHashMap();
        if (OperateType.EDIT.getVal().equals(baseDTO.getOperateType())) {
            List<MenuLanVO> existsVOS = menuLanService.findByMenuId(mainId);
            existsVOS.stream().forEach(existsVO -> {
                existsSets.put(existsVO.getLanCode(), existsVO.getId());
            });
        }
        //先处理增加，修改
        List<MenuLanVO> menuLanVOS = baseDTO.getMenuLanVOList();
        if(menuLanVOS != null) {
            for (MenuLanVO tmpVO : menuLanVOS) {
                tmpVO.setMenuId(mainId);
                tmpVO.setEnableFlag("Y");
                if (existsSets.containsKey(tmpVO.getLanCode())) {
                    tmpVO.setId(existsSets.get(tmpVO.getLanCode()));
                    existsSets.remove(tmpVO.getLanCode());
                    menuLanService.update(tmpVO);
                    continue;
                }
                menuLanService.insert(tmpVO);
            }
        }
        //然后 删除
        for (String id : existsSets.values()) {
            MenuLanVO deleteVo = new MenuLanVO();
            deleteVo.setId(id);
            menuLanService.deleteById(deleteVo);
        }
    }

    @Override
    protected void beforeDeleteOfProcess(MenuMngVO menuMngVO) {
        MenuVO paramBean = new MenuVO();
        paramBean.setParentId(menuMngVO.getId());
        paramBean.setEnableFlag("Y");
        if (getBaseMainService().hasBy(paramBean)) {
            throw new BusinessException("该菜单下有子菜单,不能删除.");
        }
        if(BusPrivCode.PRIV_SYS_ADMIN.getVal().equals(menuMngVO.getPrivCode())) {
            throw new BusinessException("系统默认管理不能删除");
        }
    }


    public List<MenuBuildVo> buildMenus(List<MenuMngVO> menuDTOS) {
        List<MenuBuildVo> list = new LinkedList<>();
        menuDTOS.forEach(menuDTO -> {
                    if (menuDTO != null) {
                        List<MenuMngVO> menuDTOList = menuDTO.getChildren();
                        MenuBuildVo menuBuildVo = new MenuBuildVo();
                        menuBuildVo.setName(menuDTO.getMenuName());
                        menuBuildVo.setPath(menuDTO.getPathUrl());

                        // 如果不是外链,即外部菜单
                        if (!BusMenuType.MENU_EXTERNAL.getVal().equals(menuDTO.getMenuType())) {
                            if (StringUtils.isBlank(menuDTO.getParentId())) {
                                //一级目录需要加斜杠，不然访问 会跳转404页面
                                menuBuildVo.setPath("/" + menuDTO.getPathUrl());
                                menuBuildVo.setComponent(StringUtils.isEmpty(menuDTO.getComponentUrl()) ? "Layout" : menuDTO.getComponentUrl());
                            } else if (!StringUtils.isEmpty(menuDTO.getComponentUrl())) {
                                menuBuildVo.setComponent(menuDTO.getComponentUrl());
                            }
                        }
                        menuBuildVo.setMeta(new MenuMetaVo(menuDTO.getMenuName(), menuDTO.getIcon()));
                        if (menuDTOList != null && menuDTOList.size() != 0) {
                            menuBuildVo.setAlwaysShow(true);
                            menuBuildVo.setRedirect("noredirect");
                            menuBuildVo.setChildren(buildMenus(menuDTOList));
                            // 处理是一级菜单并且没有子菜单的情况
                        } else if (StringUtils.isBlank(menuDTO.getParentId())) {
                            /*menuBuildVo.setComponent("Layout");
                            menuBuildVo.setAlwaysShow(true);
                            menuBuildVo.setRedirect("noredirect");*/
                            MenuBuildVo menuBuildVo1 = new MenuBuildVo();
                            menuBuildVo1.setMeta(menuBuildVo.getMeta());
                            // 非外链
                            if (!BusMenuType.MENU_EXTERNAL.getVal().equals(menuDTO.getMenuType())) {
                                menuBuildVo1.setPath("index");
                                menuBuildVo1.setName(menuBuildVo.getName());
                                menuBuildVo1.setComponent(menuBuildVo.getComponent());
                            } else {
                                menuBuildVo1.setPath(menuDTO.getPathUrl());
                            }
                            menuBuildVo.setName(null);
                            menuBuildVo.setMeta(null);
                            menuBuildVo.setComponent("Layout");
                            List<MenuBuildVo> list1 = new ArrayList<MenuBuildVo>();
                            list1.add(menuBuildVo1);
                            menuBuildVo.setChildren(list1);
                        }
                        list.add(menuBuildVo);
                    }
                }
        );

        return list;
    }

    public List<MenuMngVO> buildMenuTree(List<MenuMngVO> mngVOS) {
        List<MenuMngVO> trees = new ArrayList<>();
        for (MenuMngVO mngVO : mngVOS) {
            if (StringUtils.isBlank(mngVO.getParentId())) {
                trees.add(mngVO);
            }
            for (MenuMngVO it : mngVOS) {
                if (mngVO.getId().equals(it.getParentId())) {
                    if (mngVO.getChildren() == null) {
                        mngVO.setChildren(new ArrayList<MenuMngVO>());
                    }
                    mngVO.getChildren().add(it);
                }
            }
        }
        return trees;
    }

    public List<MenuMngVO> findAllMenu(String lanCode) {
        return getBaseMngDao().findAllMenu(lanCode);
    }

    public List<MenuMngVO> findAllValidRecord(String lanCode, String isAdmin) {
        return getBaseMngDao().findAllValidRecord(lanCode, isAdmin);
    }

    public List<MenuMngVO> findCommonAdminMenu(String lanCode) {
        return getBaseMngDao().findCommonAdminMenu(lanCode);
    }

    public List<MenuMngVO> findMenuByRoleids(Set<String> roleids, String isAdmin, String lanCode) {
        return getBaseMngDao().findMenuByRoleids(roleids,isAdmin, lanCode);
    }

    public List<MenuMngVO> findMenuPrivByRoleids(Set<String> roleids) {
        return getBaseMngDao().findMenuPrivByRoleids(roleids);
    }

}
